package com.example.config;

import com.alibaba.fastjson.JSON;
import com.example.annotation.WebApiResponseBody;
import com.example.model.WebApiResponse;
import org.springframework.core.MethodParameter;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletResponse;

/**
 * 隐式的自动装换
 * 自定义Controller结果返回拦截器
 * 启用自定义注解的返回逻辑
 * 自动对返回结果进行标准格式化包装
 */

public class WebApiHandlerMethodReturnValueHandler implements HandlerMethodReturnValueHandler {

    /**
     * 何种注解进入拦截处理
     *
     * @param methodParameter
     * @return
     */
    @Override
    public boolean supportsReturnType(MethodParameter methodParameter) {
        return methodParameter.hasMethodAnnotation(WebApiResponseBody.class) ||
                methodParameter.hasMethodAnnotation(ResponseBody.class);
    }

    /**
     * 注解处理逻辑
     *
     * @param o
     * @param methodParameter
     * @param modelAndViewContainer
     * @param nativeWebRequest
     * @throws Exception
     */
    @Override
    public void handleReturnValue(@Nullable Object o,
                                  MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest) throws Exception {
//        Assert.isInstanceOf(WebApiResponse.class, o);
        HttpServletResponse response = nativeWebRequest.getNativeResponse(HttpServletResponse.class);

        if (methodParameter.hasMethodAnnotation(WebApiResponseBody.class)) {
            WebApiResponse webApiResponse = new WebApiResponse();
            //webApiResponse.setError("success");
            webApiResponse.setData(o);
            webApiResponse.setCode(WebApiResponse.SUCCESS_CODE);
            modelAndViewContainer.setRequestHandled(true);
            response.setContentType("text/plain;charset=UTF-8");
            response.getWriter().append(JSON.toJSONString(webApiResponse)).flush();
        } else {
            modelAndViewContainer.setRequestHandled(true);
            response.setContentType("text/plain;charset=UTF-8");
            if (o instanceof String) {
                response.getWriter().write(o.toString());
            } else {
                response.getWriter().append(JSON.toJSONString(o)).flush();
            }
        }
    }
}
